<script setup lang="ts">
import { ref, onMounted } from "vue";

const props = defineProps({
  defaultText: {
    type: String,
    default: "学号姓名"
  },
  fontSize: {
    type: Number,
    default: 16
  },
  opacity: {
    type: Number,
    default: 0.2
  }
});

const watermarkDiv = ref<HTMLDivElement>();
const watermarkText = ref(props.defaultText);

const createWatermark = () => {
  const canvas = document.createElement("canvas");
  const ctx = canvas.getContext("2d");
  if (!ctx) return;

  try {
    // 从localStorage获取用户信息
    const userInfo = localStorage.getItem("user-info");
    if (userInfo) {
      const parsedInfo = JSON.parse(userInfo);
      if (parsedInfo.username) {
        watermarkText.value = parsedInfo.username.toString();
      }
    }
  } catch (error) {
    console.error("获取水印信息失败:", error);
    watermarkText.value = props.defaultText;
  }

  // 设置画布大小
  canvas.width = 300;
  canvas.height = 150;

  // 设置文字样式
  ctx.font = `${props.fontSize}px Arial`;
  ctx.fillStyle = `rgba(220, 220, 220, ${props.opacity})`;
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";

  // 旋转文字
  ctx.translate(150, 75);
  ctx.rotate(-Math.PI / 6);
  ctx.fillText(watermarkText.value, 0, 0);

  // 将水印设置为背景
  if (watermarkDiv.value) {
    watermarkDiv.value.style.backgroundImage = `url(${canvas.toDataURL()})`;
  }
};

onMounted(() => {
  createWatermark();
});

defineOptions({
  name: "Watermark"
});
</script>

<template>
  <div ref="watermarkDiv" class="watermark" />
</template>

<style scoped>
.watermark {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9999;
  width: 100%;
  height: 100%;
  pointer-events: none;
  background-repeat: repeat;
}
</style>
